package com.prs.crm.action.sms;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.courser.struts.BaseAction;
import org.courser.ui.PaginationSupport;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;

import com.prs.crm.annotation.Clew;
import com.prs.crm.domain.hr.Resume;
import com.prs.crm.domain.sms.SmsSend;
import com.prs.crm.exception.InValidException;
import com.prs.crm.service.hr.ResumeService;
import com.prs.crm.service.hr.impl.ResumeServiceImpl;
import com.prs.crm.service.sms.SmsSendService;

public class SmsSendAction extends BaseAction {
	private static final NumberFormat NUMBER_FMT = new DecimalFormat(
			"00000000000");
	private SmsSend smsSend;
	private SmsSendService smsSendService;
	private PaginationSupport pagination;
	private Integer[] ids;
	private String recipient;            //接收人
	private String acceptPhones;
    private ResumeService resumeService; 
	private File upload;
	private String uploadFileName;

	@Action("listSmsSend")
	public String listSmsSend() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				SmsSend.class);
		criteria.addOrder(Order.desc("recordTime"));
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getSmsSendService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}

	@Action("editSmsSend")
	public String editSmsSend() {
		return SUCCESS;
	}

	@Action("viewSmsSend")
	public String viewSmsSend() {
		return SUCCESS;
	}

	@Clew(results = { "success" })
	@Action(value = "submitSmsSend", results = {
			@Result(name = "success", type = "redirect", location = "editSmsSend"),
			@Result(name = "error", type = "chain", location = "editSmsSend") })
	public String submitSmsSend() {
		
		System.out.println("----"+acceptPhones);
		if(recipient != null){
			String [] recid = recipient.split("[,，]");
			for (int i = 0; i < recid.length; i++) {
				Resume resume = resumeService.getResumeByid(recid[i]);
				StringBuffer sb = new StringBuffer(acceptPhones);
				sb.append(","+resume.getMobile_No());
				acceptPhones = sb.toString();
			}
		}
		System.out.println(acceptPhones);
		
		if (acceptPhones == null || "".equals(acceptPhones)) {
			addActionError("手机号码不能为空");
			return ERROR;
		}
		if (smsSend.getMessage() == null
				|| "".equals(smsSend.getMessage().trim())) {
			addActionError("消息不能为空");
			return ERROR;
		}
		try {
			String[] phoneNos = acceptPhones.split("[;,；，]");
			this.getSmsSendService().submitSmsSend(phoneNos,
					smsSend.getMessage());
			this.setPrompt("短信提交成功");
			return SUCCESS;
		} catch (InValidException e) {
			// TODO: handle exception
			this.addActionError(e.getMessage());
			return ERROR;
		}
	}

	@Action("listBatchSmsSend")
	public String listBatchSmsSend() {
		return SUCCESS;
	}

	@Action(value = "sendBatchSms", results = { @Result(name = "success", type = "redirect", location = "listBatchSmsSend") })
	public String sendBatchSms() {
		List<SmsSend> result = null;
		if (this.getStorage().get("excel") != null) {
			result = (List<SmsSend>) this.getStorage().get("excel");
			for (SmsSend sms : result) {
				this.getSmsSendService().submitSmsSend(sms.getTelephoneNo(),
						sms.getMessage());
			}
		}
		return SUCCESS;
	}

	@Action(value = "showSmsExcel", results = { @Result(name = "success", location = "listBatchSmsSend.ftl") })
	public String showExcel() {
		List<SmsSend> result = null;
		if (this.getStorage().get("excel") != null) {
			result = (List<SmsSend>) this.getStorage().get("excel");
		}
		pagination = this.getPaginationHelper().prepare(pagination);

		List<SmsSend> viewlist = new ArrayList<SmsSend>();// 这是需要现在在界面上的是EXCEL中的哪几行
		for (int i = pagination.getStartIndex(); i < result.size()
				&& i < (pagination.getStartIndex() + pagination.getPageSize()); i++) {
			viewlist.add(result.get(i));
		}
		pagination.setTotalCount(result.size());
		int totalPage = pagination.getTotalCount() / pagination.getPageSize();
		if (totalPage * pagination.getPageSize() < pagination.getTotalCount())
			totalPage++;
		pagination.setTotalPage(totalPage);
		System.out.println(pagination.getTotalCount() + ":"
				+ pagination.getStartIndex());
		pagination.setItems(viewlist);
		return SUCCESS;
	}

	@Action(value = "readSmsImportData", results = {
			@Result(name = "success", type = "redirect", location = "showSmsExcel"),
			@Result(name = "error", type = "chain", location = "listBatchSmsSend") })
	public String importExcel() {
		if (upload == null) {
			this.addActionError("请先选择导入的Excel文件！");
			return ERROR;
		}
		List<SmsSend> depts = this.readExcel();
		if(depts==null){
			this.addActionError("Excel的前两列数据都不能为空！");
			return ERROR;
		}
		this.getStorage().save("excel", depts);
		return SUCCESS;
	}

	private List<SmsSend> readExcel() {
		List<SmsSend> lstSms = new ArrayList<SmsSend>();
		try {
			if (upload != null) {
				HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(
						upload));
				HSSFSheet sheet = workbook.getSheetAt(0); // 得到第一个sheet
				
				int rows = sheet.getPhysicalNumberOfRows(); // 得到行数             ///////////////asdfsdf
 				for (int i = 0; i < rows; i++) {
					HSSFRow row = sheet.getRow(i);
					SmsSend sms = new SmsSend();
					HSSFCell cell = row.getCell(0); // 得到列1(下标0,为第一列)
					if(cell==null){
						lstSms=null;
                    	return lstSms;
                    }
					if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
						sms.setTelephoneNo(NUMBER_FMT.format(cell
								.getNumericCellValue()));
					} else {
						sms.setTelephoneNo(cell.getRichStringCellValue()
								.getString());
					}
					cell = row.getCell(1); // 得到列
					if(cell==null){
						lstSms=null;
                    	return lstSms;
                    }
                    if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                    	if((int)cell.getNumericCellValue()==cell.getNumericCellValue()){
						  sms.setMessage((int)cell.getNumericCellValue()+"");
                    	}else{
                    		sms.setMessage(cell.getNumericCellValue()+"");
                    	}
					} else {
						sms.setMessage(cell.getRichStringCellValue().getString());
					}
					System.out.println("massage:" + sms.getMessage());
                      
					lstSms.add(sms);
					sms=null;
				}
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} // 得到excel对象

		return lstSms;
	}

	public PaginationSupport getPagination() {
		return pagination;
	}

	public void setPagination(PaginationSupport pagination) {
		this.pagination = pagination;
	}

	public Integer[] getIds() {
		return ids;
	}

	public void setIds(Integer[] ids) {
		this.ids = ids;
	}

	public void setAcceptPhones(String acceptPhones) {
		this.acceptPhones = acceptPhones;
	}

	public String getAcceptPhones() {
		return acceptPhones;
	}

	public void setSmsSend(SmsSend smsSend) {
		this.smsSend = smsSend;
	}

	public SmsSend getSmsSend() {
		return smsSend;
	}

	public void setSmsSendService(SmsSendService smsSendService) {
		this.smsSendService = smsSendService;
	}

	public SmsSendService getSmsSendService() {
		return smsSendService;
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public String getRecipient() {
		return recipient;
	}

	public void setRecipient(String recipient) {
		this.recipient = recipient;
	}

	public ResumeService getResumeService() {
		return resumeService;
	}

	public void setResumeService(ResumeService resumeService) {
		this.resumeService = resumeService;
	}
    
}
